{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "cd8530b3-b6ca-426c-9780-0a479921c9b2",
   "metadata": {},
   "source": [
    "Chapter 08\n",
    "# 将矩阵乘法打包成一个函数\n",
    "Book_1《编程不难》 | 鸢尾花书：从加减乘除到机器学习 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "726a173d-fb37-4e53-8efc-696cc43422a9",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 自定义函数\n",
    "def matrix_multiplication(A,B):\n",
    "\n",
    "    # 定义全 0 矩阵 C 用来存放结果\n",
    "    C = [[0] * len(B[0]) for i in range(len(A))]\n",
    "\n",
    "    # 遍历 A 的行\n",
    "    for i in range(len(A)): # len(A) 给出 A 的行数\n",
    "\n",
    "        # 遍历 B 的列\n",
    "        for j in range(len(B[0])):  \n",
    "        # len(B[0]) 给出 B 的列数\n",
    "\n",
    "            # 这一层相当于消去 k 所在的维度，即压缩\n",
    "            for k in range(len(B)):\n",
    "                C[i][j] += A[i][k] * B[k][j]\n",
    "                # 完成对应元素相乘，再求和\n",
    "    \n",
    "    return C"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "ab375425-00a5-40f5-88eb-a2d7874d666f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义矩阵 A 和 B\n",
    "A = [[1], [2], [3]]\n",
    "B = [[1, 2, 3]]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "72873858-0600-44b7-81ce-296450be33d0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "A @ B = \n",
      "[1, 2, 3]\n",
      "[2, 4, 6]\n",
      "[3, 6, 9]\n"
     ]
    }
   ],
   "source": [
    "print('A @ B = ')\n",
    "C = matrix_multiplication(A,B) # 调用自定义函数\n",
    "for row in C:\n",
    "    print(row)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "5ce9b9b7-4979-4833-a039-5ea2fcba6701",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "B @ A = \n",
      "[14]\n"
     ]
    }
   ],
   "source": [
    "print('B @ A = ')\n",
    "D = matrix_multiplication(B,A) # 调用自定义函数\n",
    "for row in D:\n",
    "    print(row)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
